package icu.sunway.gushenBlogBackEnd.Service.Implement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.sunway.gushenBlogBackEnd.Entity.Data.AdminUserDO;
import icu.sunway.gushenBlogBackEnd.Entity.Data.UserDO;
import icu.sunway.gushenBlogBackEnd.Entity.View.ResultVO;
import icu.sunway.gushenBlogBackEnd.Entity.View.User.*;
import icu.sunway.gushenBlogBackEnd.Mapper.AdminUserMapper;
import icu.sunway.gushenBlogBackEnd.Mapper.UserMapper;
import icu.sunway.gushenBlogBackEnd.Message.UserMessage;
import icu.sunway.gushenBlogBackEnd.Service.UserService;
import icu.sunway.gushenBlogBackEnd.utils.JwtUtil;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    final UserMapper userMapper;
    final MailServiceImpl mailService;
    final AdminUserMapper adminUserMapper;

    public UserServiceImpl(UserMapper userMapper, MailServiceImpl mailService, AdminUserMapper adminUserMapper) {
        this.userMapper = userMapper;
        this.mailService = mailService;
        this.adminUserMapper = adminUserMapper;
    }

    @Override
    public UserDO getUserById(String userId) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public ResultVO<String> updateUserInfo(String token, UserUpdateInfoVO userUpdateInfoVO) {
        try {
            String userId = JwtUtil.parseTokenAsId(token);
            QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", userId);
            UserDO userDO = getOne(queryWrapper);
            userDO.setEmail(userUpdateInfoVO.getEmail());
            userDO.setNickname(userUpdateInfoVO.getNickname());
            updateById(userDO);
            return new ResultVO<>(200, UserMessage.set_info_success, UserMessage.set_info_success);
        } catch (Exception e) {
            return new ResultVO<>(400, UserMessage.set_info_fail, e.getMessage());
        }

    }

    @Override
    public ResultVO<UserVO> getUserInfo(String token) {
        String userId = JwtUtil.parseTokenAsId(token);
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        UserDO userDO = getOne(queryWrapper);
        if (userDO != null) {
            UserVO userVO = new UserVO(userDO.getId(), userDO.getNickname(), userDO.getEmail(), userDO.getAvatar());
            return new ResultVO<>(200, UserMessage.get_info_success, userVO);
        }
        return new ResultVO<>(400, UserMessage.get_info_fail, null);
    }

    @Override
    public ResultVO<String> login(UserLoginVO userLoginVO) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userLoginVO.getEmail());
        queryWrapper.eq("password", userLoginVO.getPassword());
        UserDO userDO = getOne(queryWrapper);
        if (userDO != null) {
            String token = JwtUtil.generateToken(userDO.getId());
            return new ResultVO<>(200, UserMessage.login_success, token);
        }
        return new ResultVO<>(400, UserMessage.login_fail, null);
    }

    @Override
    public ResultVO<String> register(UserRegisterVO userRegisterVO) {
        // 两次输入密码不一致
        if (!userRegisterVO.getPassword().equals(userRegisterVO.getAgain_password())) {
            return new ResultVO<>(400, UserMessage.password_not_match, null);
        }
        // 用户已存在
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userRegisterVO.getEmail());
        if (getOne(queryWrapper) != null) {
            return new ResultVO<>(400, UserMessage.user_exist, null);
        }
        // 验证码错误
        if (!mailService.checkVerifyCode(userRegisterVO.getEmail(), userRegisterVO.getVerify_code())) {
            return new ResultVO<>(400, UserMessage.code_error, null);
        }
        UserDO userDO = new UserDO();
        userDO.setEmail(userRegisterVO.getEmail());
        userDO.setNickname(userRegisterVO.getNickname());
        userDO.setPassword(userRegisterVO.getPassword());
        userDO.setAvatar("https://gushen666.oss-cn-hangzhou.aliyuncs.com/avatars/default_avatar.svg");
        save(userDO);
        return new ResultVO<>(200, UserMessage.register_success, JwtUtil.generateToken(userDO.getId()));
    }

    @Override
    public ResultVO<Boolean> sendVerifyCodeByToken(String token) {
        String userId = JwtUtil.parseTokenAsId(token);
        UserDO userDO = getUserById(userId);
        return mailService.sendVerifyCode(userDO.getEmail());
    }

    @Override
    public ResultVO<Boolean> changePassword(UserChangePasswordVO userChangePasswordVO, String token) {
        // 两次输入密码不一致
        if (!userChangePasswordVO.getNew_password().equals(userChangePasswordVO.getAgain_password())) {
            return new ResultVO<>(400, UserMessage.password_not_match, false);
        }
        // 验证码错误
        String userId = JwtUtil.parseTokenAsId(token);
        UserDO userDO = getUserById(userId);
        if (!mailService.checkVerifyCode(userDO.getEmail(), userChangePasswordVO.getVerify_code())) {
            return new ResultVO<>(400, UserMessage.code_error, false);
        }
        // 原密码错误
        String oldPassword = userDO.getPassword();
        if (!userChangePasswordVO.getOld_password().equals(oldPassword)) {
            return new ResultVO<>(400, UserMessage.old_password_error, false);
        }
        userDO.setPassword(userChangePasswordVO.getNew_password());
        updateById(userDO);
        return new ResultVO<>(200, UserMessage.change_password_success, true);
    }

    @Override
    public ResultVO<Boolean> resetPassword(UserForgetPasswordVO userForgetPasswordVO) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userForgetPasswordVO.getEmail());
        UserDO userDO = getOne(queryWrapper);
        // 用户不存在
        if (userDO == null) {
            return new ResultVO<>(400, UserMessage.user_not_exist, false);
        }
        // 两次输入密码不一致
        if (!userForgetPasswordVO.getNew_password().equals(userForgetPasswordVO.getAgain_password())) {
            return new ResultVO<>(400, UserMessage.password_not_match, false);
        }
        // 验证码错误
        if (!mailService.checkVerifyCode(userDO.getEmail(), userForgetPasswordVO.getVerify_code())) {
            return new ResultVO<>(400, UserMessage.code_error, false);
        }
        userDO.setPassword(userForgetPasswordVO.getNew_password());
        updateById(userDO);
        return new ResultVO<>(200, UserMessage.reset_password_success, true);
    }

    @Override
    public ResultVO<Boolean> checkAdmin(String token) {
        if (token == null) {
            return new ResultVO<>(400, UserMessage.user_not_login, false);
        }
        AdminUserDO adminUserDo = adminUserMapper.selectById(JwtUtil.parseTokenAsId(token));
        if (adminUserDo == null) {
            return new ResultVO<>(400, UserMessage.check_admin_user_fail, false);
        }
        return new ResultVO<>(200, UserMessage.check_admin_user_success, true);
    }

    @Override
    public ResultVO<Boolean> updateUserAvatar(String avatar, String token) {
        try {
            String userId = JwtUtil.parseTokenAsId(token);
            UpdateWrapper<UserDO> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", userId);
            updateWrapper.set("avatar", avatar);
            update(updateWrapper);
        } catch (Exception e) {
            return new ResultVO<>(400, UserMessage.update_user_avatar_fail, false);
        }
        return new ResultVO<>(200, UserMessage.update_user_avatar_success, true);
    }

}
